package net.fdukedom.epicurus.client.util;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import net.fdukedom.epicurus.service.interaction.XMLHelper;

import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * 
 * @author Alexander Kirakozov
 */
public class ConfigurationHelper extends XMLHelper {
	/**
	 * Configuration file name
	 */
	static final private String configFileName = "config.xml";

	/**
	 * Prefix of xPath
	 */
	static final private String configPrefix = "//config/";

	/**
	 * Server url element
	 */
	static final private String serverURL = "serverurl";

	/**
	 * Constructor
	 */
	public ConfigurationHelper() {
		super();
		createDocument();
	}

	/**
	 * Loads options from xml file
	 * 
	 * @return true if file was loaded succesfully
	 */
	public void createDocument() {
		SAXBuilder builder = new SAXBuilder();

		try {
			doc = builder.build(configFileName);
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Returns server URL
	 * 
	 * @return server URL
	 */
	public String getServerURL() {
		return getElementValueByXPath(configPrefix + serverURL);
	}

	/**
	 * Sets server URL
	 * 
	 * @return server URL
	 */
	public void setServerURL(String value) {
		setElementValueByXPath(configPrefix + serverURL, value);
	}

	/**
	 * Saves current xml options
	 * 
	 */
	public void save() {
		try {
			XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
			Writer jdomWriter = new BufferedWriter(new FileWriter(
					configFileName));

			outputter.output(doc, jdomWriter);
			jdomWriter.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
